package com.qd.qx.ui.module2;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.animation.ScaleInAnimation;
import com.aspsine.irecyclerview.universaladapter.ViewHolderHelper;
import com.aspsine.irecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.qd.common.base.BaseFragment;
import com.qd.common.baserx.RxSubscriber;
import com.qd.common.commonutils.ImageLoaderUtils;
import com.qd.common.commonutils.JsonUtils;
import com.qd.common.commonutils.ToastUitl;
import com.qd.qx.R;
import com.qd.qx.api.Api;
import com.qd.qx.api.ApiServerConstants;
import com.qd.qx.bean.CommonUserGroupBean;
import com.qd.qx.bean.MessageInfoBean;
import com.qd.qx.bean.PeopleBean;
import com.qd.qx.bean.PeopleContactsBean;
import com.qd.qx.bean.TongxunluBean;
import com.qd.qx.bean.UserData;
import com.qd.qx.im.ChatInfoUtils;
import com.qd.qx.ui.main.activity.ChatActivity;
import com.qd.chatui.util.MyUtils;
import com.qd.qx.widget.NineGridImageView;
import com.qd.qx.widget.NineGridImageViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Code is far away from bug with the animal protecting
 * Author：YS on 2018/10/11
 * Function：通讯录模块 子模块内容
 */
public class TXLChildFragment extends BaseFragment {


    @BindView(R.id.txlChildIrcv)
    IRecyclerView txlChildIrcv;
    CommonRecycleViewAdapter txlAdapter;
    CommonRecycleViewAdapter groupAdapter;
    CommonRecycleViewAdapter contactAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_txl_child;
    }

    @Override
    public void initPresenter() {

    }


    @Override
    public void initView() {
        Bundle bundle = getArguments();
        int type = 0;
        if (null != bundle) {
            type = bundle.getInt("type");
        }
        switch (type) {
            //联系人
            case 1:
                tongxunluAction();
                requestTongxunlu();
                break;
            //群组
            case 2:
                groupAction();
                requestCommonUseGroup();
                break;
            //常用联系人
            case 3:
                peopleAction();
                requestContacts();
                break;
        }

    }

    /**
     * 刷新数据
     */
    public void refresh(int index) {
        switch (index) {
            case 0:
                requestTongxunlu();
                break;
            case 1:
                requestCommonUseGroup();
                break;
            case 2:
                requestContacts();
                break;
        }

    }

    /**
     * 头像9宫格适配器
     */
    private NineGridImageViewAdapter<PeopleBean> nineGridImageViewAdapter = new NineGridImageViewAdapter<PeopleBean>() {
        @Override
        protected void onDisplayImage(Context context, ImageView imageView, PeopleBean bean) {
            MyUtils.displayUserHeader(context, imageView, bean.getHeaderImg(), bean.getName());
        }

        @Override
        protected ImageView generateImageView(Context context) {
            return super.generateImageView(context);
        }
    };


    private void requestTongxunlu() {
        Map<String, String> map = new HashMap<>();
        map.put("deptid", "0");
        if (null == mRxManager) {
            return;
        }
        mRxManager.add((Api.getDefault().requestTongXunLu(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(getActivity(), false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        TongxunluBean tongxunluBean = (TongxunluBean) JsonUtils.ObjectToBean(messageInfoBean.getData(), TongxunluBean.class);
                        if (null != tongxunluBean) {
                            if (null != txlAdapter) {
                                txlAdapter.clear();
                                txlAdapter.addAll(tongxunluBean.getDeptList());
                                txlAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }

    /**
     * 获取常用联系人列表
     */
    private void requestContacts() {
        Map<String, String> map = new HashMap<>();
        map.put("userCode", UserData.getInstance().getRefCode());
        if (null == mRxManager) {
            return;
        }
        mRxManager.add((Api.getDefault().getContacts(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(getActivity(), false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        PeopleContactsBean peopleContactsBean = (PeopleContactsBean) JsonUtils.ObjectToBean(messageInfoBean, PeopleContactsBean.class);
                        if (null != peopleContactsBean) {
                            if (null != contactAdapter) {
                                contactAdapter.clear();
                                contactAdapter.addAll(peopleContactsBean.getData());
                                contactAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort("请求失败" + message);
                    }
                }));

    }

    /**
     * 获取常用群组列表
     */
    private void requestCommonUseGroup() {
        Map<String, String> map = new HashMap<>();
        map.put("userCode", UserData.getInstance().getRefCode());
        if (null == mRxManager) {
            return;
        }
        mRxManager.add((Api.getDefault().getCommonUseGroup(Api.newRequestBody(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<MessageInfoBean>(getActivity(), false) {
                    @Override
                    protected void _onNext(MessageInfoBean messageInfoBean) {
                        CommonUserGroupBean commonUserGroupBean = (CommonUserGroupBean) JsonUtils.ObjectToBean(messageInfoBean, CommonUserGroupBean.class);
                        if (null != commonUserGroupBean.getData()) {
                            if (null != groupAdapter) {
                                groupAdapter.clear();
                                groupAdapter.addAll(commonUserGroupBean.getData());
                                groupAdapter.notifyDataSetChanged();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUitl.showShort(message);
                    }
                }));

    }

    /**
     * 通讯录设置
     */
    private void tongxunluAction() {
        txlAdapter = new CommonRecycleViewAdapter<TongxunluBean.DeptListBean>(getActivity(), R.layout.txl_ircv_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final TongxunluBean.DeptListBean bean) {
                helper.setText(R.id.tvName, bean.getDeptName());
                //   helper.setText(R.id.tvLeader, "(负责人: " + bean.getLeader() + ")");
                // helper.setText(R.id.tvAllCount, bean.getTotalPeople());
                ImageView imageView = helper.getView(R.id.ivHeader);
                ImageLoaderUtils.displayRound(getActivity(), imageView, bean.getDeptHeadImg());
                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TongxunluChildActivity.startAction(getActivity(), bean.getDeptid(), bean.getDeptName());

                    }
                });
            }
        };
        txlChildIrcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<TongxunluBean.DeptListBean> deptList = new ArrayList<>();
        txlAdapter.addAll(deptList);
        txlAdapter.openLoadAnimation(new ScaleInAnimation());
        txlChildIrcv.setAdapter(txlAdapter);
    }


    /**
     * 群组设置
     */
    private void groupAction() {
        groupAdapter = new CommonRecycleViewAdapter<CommonUserGroupBean.DataBean>(getActivity(), R.layout.txl_ircv_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final CommonUserGroupBean.DataBean bean) {
                helper.setText(R.id.tvName, bean.getGroupName());
                helper.setText(R.id.tvLeader, "");
                helper.setText(R.id.tvAllCount, "");
                final NineGridImageView nineGridImageView = helper.getView(R.id.nineImg);
                FrameLayout flSingeShow = helper.getView(R.id.flSingeShow);
                flSingeShow.setVisibility(View.GONE);//把显示一个人的view隐藏
                nineGridImageView.setAdapter(nineGridImageViewAdapter);
                final List<PeopleBean> stringList = new ArrayList<>();
                //服务器返回的只是@前面的id  数据库存的是整个 id+@conference.+ip
                String jid = bean.getGroupId() + "@conference." + ApiServerConstants.IM_URL;
                ChatInfoUtils.getInstance().getUserInfo(jid, new ChatInfoUtils.ChatInfoCallBack() {
                    @Override
                    public void callBack(Object object) {
                        if (null != object) {
                            List<PeopleBean> imgList = (List<PeopleBean>) object;
                            stringList.addAll(imgList);
                        } else {
                            //stringList.add(new );
                        }
                        if (stringList.size() == 1) {
                            nineGridImageView.setGap(0);
                            nineGridImageView.setBackground(null);
                        }
                        nineGridImageView.setImagesData(stringList);
                    }
                });
                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ChatActivity.startAction(getActivity(), -1, bean.getGroupId() + "@conference." + ApiServerConstants.IM_URL, bean.getGroupName());
                    }
                });
            }
        };
        txlChildIrcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<CommonUserGroupBean.DataBean> commonGroupList = new ArrayList<>();
        groupAdapter.addAll(commonGroupList);
        groupAdapter.openLoadAnimation(new ScaleInAnimation());
        txlChildIrcv.setAdapter(groupAdapter);
    }


    /**
     * 常用联系人设置
     */
    private void peopleAction() {
        contactAdapter = new CommonRecycleViewAdapter<PeopleContactsBean.DataBean>(getActivity(), R.layout.txl_ircv_itemlayout) {
            @Override
            public void convert(ViewHolderHelper helper, final PeopleContactsBean.DataBean bean) {

                helper.setText(R.id.tvName, bean.getName());
                helper.setText(R.id.tvLeader, "");
                helper.setText(R.id.tvAllCount, "");
                ImageView imageView = helper.getView(R.id.ivHeader);
                MyUtils.displayUserHeader(getActivity(), imageView, bean.getHeadImg(), bean.getName());
                helper.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PeopleInfoActivity.startAction(getActivity(), bean.getAccount());
                    }
                });
            }
        };
        txlChildIrcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        List<PeopleContactsBean.DataBean> data = new ArrayList<>();
        contactAdapter.addAll(data);
        contactAdapter.openLoadAnimation(new ScaleInAnimation());
        txlChildIrcv.setAdapter(contactAdapter);
    }
}
